{% extends 'paper/base.html' %}
{% block header %}
    <link rel="stylesheet" href="/static/backtotop.css">
{% endblock %}
{% block content %}
    <h3><span class="badge badge-primary badge">新加题目/概念</span></h3>
    <form id="my-awesome-dropzone">
        <div class="row">
            <div class="col-6">
                <label for="course"><span class="badge badge-info badge">科目</span></label>
                <select name="course" id="course" class="form-control">
                    {% for c in courses %}
                        <option value="{{ c }}">{{ c }}</option>
                    {% endfor %}
                </select>
            </div>
        </div>
        <div class="row">
            <div class="col-6">
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="type" id="inlineRadio1"
                           value="问题" checked>
                    <label class="form-check-label" for="inlineRadio1">问题</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="type" id="inlineRadio2"
                           value="概念">
                    <label class="form-check-label" for="inlineRadio2">概念</label>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-6">
                <label for="id_subject"><span class="badge badge-info badge">题型名称</span></label>
                <input type="text" name="subject" id="id_subject" class="form-control" autocomplete="false" required/>
            </div>
        </div>
        <div class="row">
            <div class="col-6">
                <label for="id_title"><span class="badge badge-info badge">标题</span></label>
                <input type="text" name="title" id="id_title" class="form-control" autocomplete="false" required/>
            </div>
        </div>
        <div class="row">
            <div class="col-auto">
                <input type="file" name="question" id="question" accept="image/png, image/jpeg" hidden/>
            </div>
        </div>
        <div class="row">
            <div class="col-auto">
                <input type="file" name="answer" id="answer" accept="image/png, image/jpeg" hidden/>
            </div>
        </div>
        <div class="row">
            <div class="col-auto">
                <input type="file" name="analyze" id="analyze" accept="image/png, image/jpeg" hidden/>
            </div>
        </div>
        <div><span class="badge badge-info badge">问题：</span></div>
        <div class="row">
            <div class="col-sm-12 col-xl-6">
                <canvas id="c_question" height="100" style="border:1px solid grey;"></canvas>
            </div>
        </div>
        <div><span class="badge badge-info badge">答案：</span></div>
        <div class="row">
            <div class="col-sm-12 col-xl-6">
                <canvas id="c_answer" height="100" style="border:1px solid grey;"></canvas>
            </div>
        </div>
        <div><span class="badge badge-info badge">讲解：</span></div>
        <div class="row">
            <div class="col-sm-12 col-xl-6">
                <canvas id="c_analyze" height="100" style="border:1px solid grey;"></canvas>
            </div>
        </div>
        <div class="row">
            <div class="col-auto">
                <button type="submit" class="btn btn-primary">提交</button>
            </div>
        </div>
    </form>
    <!-- 信息提示 -->
    <div class="toast" id="id_toast_success" style="position: absolute; top: 300px; right: 300px;">
        <div class="toast-header">
            <strong class="mr-auto">Hi</strong>
        </div>
        <div class="toast-body">
            成功保存.
        </div>
    </div>
    <!-- Return to Top -->
    <a href="javascript:" id="return-to-top"><i class="icon-chevron-up">Top</i></a>
{% endblock %}
{% block script %}
    <script>
        $(window).scroll(function () {
            if ($(this).scrollTop() >= 50) {        // If page is scrolled more than 50px
                $('#return-to-top').fadeIn(200);    // Fade in the arrow
            } else {
                $('#return-to-top').fadeOut(200);   // Else fade out the arrow
            }
        });
        $('#return-to-top').click(function () {      // When arrow is clicked
            $('body,html').animate({
                scrollTop: 0                       // Scroll to top of body
            }, 500);
        });

    </script>
    <script>
        $(document).ready(function () {
            let form = document.getElementById('my-awesome-dropzone');

            let questionInput = document.getElementById("question");
            let questionCanvas = document.getElementById("c_question");
            let answerInput = document.getElementById("answer");
            let answerCanvas = document.getElementById("c_answer");
            let analyzeInput = document.getElementById("analyze");
            let analyzeCanvas = document.getElementById("c_analyze");

            let currentInput = questionInput;
            let currentCanvas = questionCanvas;

            // 保留canvas尺寸
            let canvas_w = answerCanvas.width;
            let canvas_h = answerCanvas.height;

            let dict = {
                'c_question': [questionInput, questionCanvas],
                'c_answer': [answerInput, answerCanvas],
                'c_analyze': [analyzeInput, analyzeCanvas],
            };

            /**
             * This handler retrieves the images from the clipboard as a blob and returns it in a callback.
             *
             * @param pasteEvent
             * @param callback
             */
            function retrieveImageFromClipboardAsBlob(pasteEvent, callback) {
                if (pasteEvent.clipboardData === false) {
                    if (typeof (callback) == "function") {
                        callback(undefined);
                    }
                }

                let items = pasteEvent.clipboardData.items;
                if (items === undefined) {
                    if (typeof (callback) == "function") {
                        callback(undefined);
                    }
                }

                for (let i = 0; i < items.length; i++) {
                    // Skip content if not image
                    if (items[i].type.indexOf("image") === -1) continue;
                    // Retrieve image on clipboard as blob
                    let blob = items[i].getAsFile();

                    if (typeof (callback) == "function") {
                        callback(blob);
                    }
                }
            }

            window.addEventListener('paste', e => {
                currentInput.files = e.clipboardData.files;
                // Handle the event
                retrieveImageFromClipboardAsBlob(e, function (imageBlob) {
                    // If there's an image, display it in the canvas
                    if (imageBlob) {
                        let canvas = currentCanvas;
                        let ctx = canvas.getContext('2d');
                        // Create an image to render the blob on the canvas
                        let img = new Image();
                        // Once the image loads, render the img on the canvas
                        img.onload = function () {
                            // Update dimensions of the canvas with the dimensions of the image
                            canvas.width = this.width;
                            canvas.height = this.height;
                            // Draw the image
                            ctx.drawImage(img, 0, 0);
                        };

                        // Cross browser support for URL
                        let URLObj = window.URL || window.webkitURL;
                        // Creates a DOMString containing a URL representing the object given in the parameter
                        // namely the original Blob
                        img.src = URLObj.createObjectURL(imageBlob);
                    }
                });
            });

            // 表单提交
            function clear_data(canvas, input) {
                let ctx = canvas.getContext('2d');
                ctx.setTransform(1, 0, 0, 1, 0, 0);
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                input.value = '';
            }

            $('#my-awesome-dropzone').submit(function (e) {
                e.preventDefault();
                let myForm = document.getElementById('my-awesome-dropzone');
                let formdata = new FormData(myForm);
                $.ajax({
                    type: 'POST',
                    url: "/paper/p/",
                    data: formdata,
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        // console.log(data);
                        if (data.status) {
                            let id_toast = $('#id_toast_success');
                            id_toast.toast({delay: 2000});
                            id_toast.toast('show');
                            // 清空数据
                            clear_data(questionCanvas, questionInput);
                            clear_data(answerCanvas, answerInput);
                            clear_data(analyzeCanvas, analyzeInput);

                        } else {
                            // $('#id_toast_success').toast('show');
                            alert('提交错误：' + data.err)
                        }

                    }
                });
            });


            $('canvas').click(function (e) {
                // console.log(e.target.id);
                currentInput = dict[e.target.id][0];
                currentCanvas = dict[e.target.id][1];
                // 清除所有样式，设置当前样式
                $('canvas').css('border', '1px solid grey');
                $('#' + e.target.id).css('border', '1px solid blue');
            });

            // ready
        });
    </script>
{% endblock %}